#!/usr/bin/env node

const { exec } = require("child_process");
const path = require("path");
const chalk = require("chalk");
const yargs = require("yargs");
const covert = require("./covert");
const { logInfo } = require('./utils')


const PDF_2_HTML_EX_CMD = "/usr/local/bin/pdf2htmlEX";

function getPdf2htmlExArgv() {
  const argv = process.argv;
  const others = argv.slice(2);
  if (others[0] === "pdf2htmlEX") {
    others.shift();
  }
  others.unshift(PDF_2_HTML_EX_CMD);
  return others;
}

function transformPdfName(pdfName) {
  const matches = pdfName.match(/[^/]+$/);
  let fileName = "";
  if (matches) {
    fileName = matches[0];
    const idx = fileName.lastIndexOf(".");
    fileName = fileName.substring(0, idx);
    fileName += ".html";
  }
  return fileName;
}

function covertHtml() {
  const argv = process.argv;
  let fileDir = "";
  if (argv.length) {
    fileDir = argv[argv.length - 1];
  }

  const outDir = yargs.argv["destDir"];
  if (!fileDir) {
    throw new Error("未识别到文件名参数！");
  } else {
    const htmlName = transformPdfName(fileDir);
    let htmlDir = htmlName;
    if (outDir) {
      htmlDir = path.join(outDir, htmlDir);
    }
    covert(htmlDir, outDir);
  }
}

async function runPdf2htmlEx() {
  const args = getPdf2htmlExArgv();
  const pdf2htmlExCmd = args.join(" ");
  logInfo(`\nstart executing: ${pdf2htmlExCmd}\n`) 
  const child = exec(pdf2htmlExCmd, (error, stdout, stderr) => {
    if (error) {
      console.error(error);
      return;
    }
    console.log(stdout);
    logInfo(`finished pdf2htmlEx...\n`)
    logInfo(`\nstart extracting base64 images...: ${pdf2htmlExCmd}\n`)  
    covertHtml();
    logInfo(`finish extracting\n`)
  });

  child.stdout.setEncoding('utf8');

  child.stdout.on("data", function (data) {
    console.log(data.toString());
  });
}

runPdf2htmlEx();
